package com.hyzh.latte.vehicle.nezha;

import cn.hutool.core.collection.CollectionUtil;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author songkui
 * @since 2024/3/22 10:07
 */
@Getter
@NoArgsConstructor
public class ParkClientCamera {

    //key: cameraCode;   v: Set<SessionId>;
    private final ConcurrentHashMap<String, Set<String>> cameraMap = new ConcurrentHashMap<>();

    // key: sessionId,   v: SessionId   ALL camera
    private final  ConcurrentHashMap<String, String> allCameraMap = new ConcurrentHashMap<>();

    public void removeCameraMap(NezhaClient client){

        Set<String> cms = client.getCameras();
        if (CollectionUtil.isNotEmpty(cms)){
            for (String oc : cms){
                Set<String> sset =  cameraMap.get(oc);
                if (null != sset){
                    sset.remove(client.getSessionId());
                }
            }
        }
        allCameraMap.remove(client.getSessionId());
    }

    public void switchCamera(NezhaClient client, Set<String> newCamera, boolean isALL){
        removeCameraMap(client);
        if (isALL){
            allCameraMap.put(client.getSessionId(), client.getSessionId());
        }else if (CollectionUtil.isNotEmpty(newCamera)){
            for (String nc : newCamera){
                Set<String> sset = cameraMap.computeIfAbsent(nc, k -> new HashSet<>());
                sset.add(client.getSessionId());
            }
        }
    }

    public Set<String> listSessionIdByCameraCode(String cameraCode){

        Set<String> sset =  cameraMap.get(cameraCode);
        if (CollectionUtil.isEmpty(sset) && CollectionUtil.isEmpty(allCameraMap)){
            return null;
        }

        Set<String> sessionIdSet = new HashSet<>();
        if (CollectionUtil.isNotEmpty(sset)){
            sessionIdSet.addAll(sset);
        }
        sessionIdSet.addAll(allCameraMap.keySet());

        return sessionIdSet;
    }


}
